<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" :rules="searchRule" @keyup.enter="onSubmit">
      <el-form-item label="创建日期" prop="createdAt">
      <template #label>
        <span>
          创建日期
          <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </span>
      </template>
      <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始日期" :disabled-date="time=> searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"></el-date-picker>
       —
      <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束日期" :disabled-date="time=> searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"></el-date-picker>
      </el-form-item>
        <el-form-item label="工号:" prop="ID">
          <el-input v-model="searchInfo.ID" :clearable="true"  placeholder="请输入员工工号" />
        </el-form-item>
        <el-form-item label="员工姓名:" prop="username">
          <el-input v-model="searchInfo.username" :clearable="true"  placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="性别:" prop="sex">
          <el-radio  v-model="searchInfo.sex" :label=true>男</el-radio>
          <el-radio  v-model="searchInfo.sex" :label=false>女</el-radio>
        </el-form-item>
        <el-form-item label="职位:" prop="job">
          <el-select v-model="searchInfo.job" class="m-2" placeholder="请输入职位" size="small">
            <el-option
                v-for="item in jobs"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="进出状态:" prop="outinstatus">
          <el-radio v-model="searchInfo.outinstatus" :label=true>进</el-radio>
          <el-radio v-model="searchInfo.outinstatus" :label=false>出</el-radio>
        </el-form-item>
        <el-form-item label="考勤状态:" prop="examstatus">
          <el-radio v-model="searchInfo.examstatus" :label=true>正常</el-radio>
          <el-radio v-model="searchInfo.examstatus" :label=false>异常</el-radio>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
        <div class="gva-btn-list">
            <el-button type="primary" icon="plus" @click="openDialog">新增</el-button>
            <el-popover v-model:visible="deleteVisible" :disabled="!multipleSelection.length" placement="top" width="160">
            <p>确定要删除吗？</p>
            <div style="text-align: right; margin-top: 8px;">
                <el-button type="primary" link @click="deleteVisible = false">取消</el-button>
                <el-button type="primary" @click="onDelete">确定</el-button>
            </div>
            <template #reference>
                <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="deleteVisible = true">删除</el-button>
            </template>
            </el-popover>
        </div>
        <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        @selection-change="handleSelectionChange"
        >
        <el-table-column type="selection" width="55" />
          <el-table-column align="left" label="员工姓名" prop="username" width="120" />
          <el-table-column align="left" label="员工性别" prop="sex" width="120">
            <template #default="scope">{{ scope.row.sex ? '男性' : '女性' }} </template>
          </el-table-column>
          <el-table-column align="left" label="职位" prop="job" width="120" />
          <el-table-column align="left" label="部门" prop="department" width="120" />
          <el-table-column align="left" label="员工手机号" prop="tel" width="120" />
          <el-table-column align="left" label="进出状态" prop="outinstatus" width="120">
            <template #default="scope">{{ scope.row.outinstatus ? '进' : '出' }}</template>
          </el-table-column>
        <el-table-column align="left" label="门禁卡状态" prop="accessstatus" width="120">
            <template #default="scope">{{ scope.row.accessstatus ? '开启' : '关闭' }}</template>
        </el-table-column>
        <el-table-column align="left" label="考期状态" prop="examstatus" width="120">
            <template #default="scope">{{ scope.row.examstatus ? '正常' : '异常' }}</template>
        </el-table-column>
<!--        <el-table-column align="left" label="人脸图像" prop="faceimg" width="120" />-->
<!--        <el-table-column align="left" label="身份证地址" prop="idaddr" width="120" />-->
<!--        <el-table-column align="left" label="身份证号" prop="idcard" width="120" />-->
<!--        <el-table-column align="left" label="身份证照片" prop="idcardimg" width="120" />-->
<!--        <el-table-column align="left" label="员工民族" prop="nation" width="120" />-->
<!--        <el-table-column align="left" label="员工籍贯" prop="native" width="120" />-->
        <el-table-column align="left" label="操作">
            <template #default="scope">
            <el-button type="primary" link class="table-button" @click="getDetails(scope.row)">
                <el-icon style="margin-right: 5px"><InfoFilled /></el-icon>
                查看详情
            </el-button>
            <el-button type="primary" link icon="edit" class="table-button" @click="updateStaffFunc(scope.row)">变更</el-button>
            <el-button type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button>
            </template>
        </el-table-column>
        </el-table>
        <div class="gva-pagination">
            <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            />
        </div>
    </div>
    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="type==='create'?'添加':'修改'" destroy-on-close>
      <el-scrollbar height="500px">
          <el-form :model="formData" label-position="right" ref="elFormRef" :rules="rule" label-width="80px">
            <el-form-item label="员工姓名:"  prop="username" >
              <el-input v-model="formData.username" :clearable="true"  placeholder="请输入员工姓名" />
            </el-form-item>
            <el-form-item label="员工性别:"  prop="sex" >
               <el-radio v-model="formData.sex" :label=true>男</el-radio>
               <el-radio v-model="formData.sex" :label=false>女</el-radio>
<!--              <el-switch v-model="formData.sex" active-color="#13ce66" inactive-color="#ff4949" active-text="男" inactive-text="女" clearable ></el-switch>-->
            </el-form-item>
            <el-form-item label="员工民族:"  prop="nation" >
              <el-select v-model="formData.nation" class="m-2" placeholder="请输入员工民族" size="small">
                <el-option
                    v-for="item in nations"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
<!--              <el-input v-model="formData.nation" :clearable="true"  placeholder="请输入员工民族" />-->
            </el-form-item>
            <el-form-item label="员工籍贯:"  prop="native" >
              <el-select v-model="formData.native" class="m-2" placeholder="请输入员工籍贯" size="small">
                <el-option
                    v-for="item in natives"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
<!--              <el-input v-model="formData.native" :clearable="true"  placeholder="请输入员工籍贯" />-->
            </el-form-item>
            <el-form-item label="员工手机号:"  prop="tel" >
              <el-input v-model="formData.tel" :clearable="true"  placeholder="请输入员工手机号" />
            </el-form-item>
            <el-form-item label="身份证号:"  prop="idcard" >
              <el-input v-model="formData.idcard" :clearable="true" placeholder="请输入身份证号" />
            </el-form-item>
            <el-form-item label="身份证地址:"  prop="idaddr" >
              <el-input v-model="formData.idaddr" :clearable="true"  placeholder="请输入身份证地址" />
            </el-form-item>
            <el-form-item
                label="身份证照片"
                label-width="80px"
            >
              <div
                  style="display:inline-block"
                  @click="openHeaderChange1"
              >
                <img
                    v-if="formData.idcardimg"
                    alt="头像"
                    class="header-img-box"
                    :src="(formData.idcardimg && formData.idcardimg.slice(0, 4) !== 'http')?path+formData.idcardimg:formData.idcardimg"
                >
                <div
                    v-else
                    class="header-img-box"
                >从媒体库选择</div>
              </div>
            </el-form-item>
            <el-form-item label="职位:"  prop="job" >
              <el-select v-model="formData.job" class="m-2" placeholder="请输入职位" size="small">
                <el-option
                    v-for="item in jobs"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
<!--              <el-input v-model="formData.job" :clearable="true"  placeholder="请输入职位" />-->
            </el-form-item>
            <el-form-item label="部门:"  prop="department" >
              <el-select v-model="formData.department" class="m-2" placeholder="请输入部门" size="small">
                <el-option
                    v-for="item in departments"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
<!--              <el-input v-model="formData.department" :clearable="true"  placeholder="请输入部门" />-->
            </el-form-item>
            <el-form-item label="进出状态:"  prop="outinstatus" >
              <el-switch v-model="formData.outinstatus" active-color="#13ce66" inactive-color="#ff4949" active-text="进" inactive-text="出" clearable ></el-switch>
            </el-form-item>
            <el-form-item
                label="头像"
                label-width="80px"
            >
              <div
                  style="display:inline-block"
                  @click="openHeaderChange"
              >
                <img
                    v-if="formData.faceimg"
                    alt="头像"
                    class="header-img-box"
                    :src="(formData.faceimg && formData.faceimg.slice(0, 4) !== 'http')?path+formData.faceimg:formData.faceimg"
                >
                <div
                    v-else
                    class="header-img-box"
                >从媒体库选择</div>
              </div>
            </el-form-item>
            <el-form-item label="门禁卡状态:"  prop="accessstatus" >
              <el-switch v-model="formData.accessstatus" active-color="#13ce66" inactive-color="#ff4949" active-text="开启" inactive-text="关闭" clearable ></el-switch>
            </el-form-item>
            <el-form-item label="考期状态:"  prop="examstatus" >
              <el-switch v-model="formData.examstatus" active-color="#13ce66" inactive-color="#ff4949" active-text="正常" inactive-text="异常" clearable ></el-switch>
            </el-form-item>
          </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <ChooseImg
        ref="chooseImg"
        :target="formData"
        :target-key="`faceimg`"
    />
    <ChooseImg2
        ref="chooseImg2"
        :target="formData"
        :target-key="`idcardimg`"
    />
    <el-dialog v-model="detailShow" style="width: 800px" lock-scroll :before-close="closeDetailShow" title="查看详情" destroy-on-close>
      <el-scrollbar height="550px">
        <el-descriptions column="1" border>
          <el-descriptions-item label="员工姓名">
            {{ formData.username }}
          </el-descriptions-item>
          <el-descriptions-item label="员工性别">
            {{ formData.sex ? '男性' : '女性' }}
          </el-descriptions-item>

          <el-descriptions-item label="员工民族">
            {{ formData.nation }}
          </el-descriptions-item>
          <el-descriptions-item label="员工籍贯">
            {{ formData.native }}
          </el-descriptions-item>
          <el-descriptions-item label="员工手机号">
            {{ formData.tel }}
          </el-descriptions-item>

          <el-descriptions-item label="身份证号">
            {{ formData.idcard }}
          </el-descriptions-item>
          <el-descriptions-item label="身份证地址">
            {{ formData.idaddr }}
          </el-descriptions-item>
          <el-descriptions-item label="身份证照片">
            <div
                style="display:inline-block"
                @click="openHeaderChange"
            >
              <img
                  alt="头像"
                  class="header-img-box"
                  :src="(formData.idcardimg && formData.idcardimg.slice(0, 4) !== 'http')?path+formData.idcardimg:formData.idcardimg"
              >

            </div>
          </el-descriptions-item>
          <el-descriptions-item label="职位">
            {{ formData.job }}
          </el-descriptions-item>
          <el-descriptions-item label="部门">
            {{ formData.department }}
          </el-descriptions-item>
          <el-descriptions-item label="进出状态">
            {{ formData.outinstatus ? '进' : '出' }}
          </el-descriptions-item>
          <el-descriptions-item label="人脸图像"  label-width="80px">
            <div
                style="display:inline-block"
                @click="openHeaderChange"
            >
              <img
                  alt="头像"
                  class="header-img-box"
                  :src="(formData.faceimg && formData.faceimg.slice(0, 4) !== 'http')?path+formData.faceimg:formData.faceimg"
              >

            </div>
            <!--                        {{ formData.faceimg }}-->
          </el-descriptions-item>
          <el-descriptions-item label="门禁卡状态">
            {{ formData.outinstatus ? '开启' : '关闭' }}
                </el-descriptions-item>
                <el-descriptions-item label="考勤状态">
                  {{ formData.examstatus ? '正常' : '异常' }}
                </el-descriptions-item>
          <el-descriptions-item label="进入日期">
            2023-11-14 19:50
          </el-descriptions-item>
<!--          <el-form-item-->
<!--              label="头像"-->
<!--              label-width="80px"-->
<!--          >-->
<!--            <div-->
<!--                style="display:inline-block"-->
<!--                @click="openHeaderChange"-->
<!--            >-->
<!--              <img-->
<!--                  v-if="userInfo.headerImg"-->
<!--                  alt="头像"-->
<!--                  class="header-img-box"-->
<!--                  :src="(userInfo.headerImg && userInfo.headerImg.slice(0, 4) !== 'http')?path+userInfo.headerImg:userInfo.headerImg"-->
<!--              >-->
<!--              <div-->
<!--                  v-else-->
<!--                  class="header-img-box"-->
<!--              >从媒体库选择</div>-->
<!--            </div>-->
<!--          </el-form-item>-->





        </el-descriptions>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  createStaff,
  deleteStaff,
  deleteStaffByIds,
  updateStaff,
  findStaff,
  getStaffList
} from '@/api/staff'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'

import CustomPic from '@/components/customPic/index.vue'
import ChooseImg from '@/components/chooseImg/index.vue'
import ChooseImg2 from '@/components/chooseImg/index.vue'
import WarningBar from '@/components/warningBar/warningBar.vue'

defineOptions({
    name: 'Staff'
})

const path = ref(import.meta.env.VITE_BASE_API + '/')
// 自动化生成的字典（可能为空）以及字段
const genderOptions = ref([])
const formData = ref({
        created_at:formatDate(),
        accessstatus: false,
        department: '',
        examstatus: false,
        faceimg: '',
        idaddr: '',
        idcard: '',
        idcardimg: '',
        ishere: false,
        job: '',
        nation: '',
        native: '',
        outinstatus: false,
        sex: false,
        tel: '',
        username: '',
        })
// 验证规则
const rule = reactive({
  tel: [
    { required: true, message: "请输入联系方式", trigger: "blur" },
    { min: 11, max: 11, message: "请输入11位手机号码", trigger: "blur" },
    {
      pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
      //pattern: /^1[3456789]\d{9}$/,
      message: "请输入正确的手机号码",
    },
  ],
  idcard: [
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号码",
    }
  ]
})
//
const nations = [
  {
    value: '汉族',
    label: '汉族',
  },
  {
    value: '蒙古组',
    label: '蒙古组',
  },
  {
    value: '维吾尔族',
    label: '维吾尔族',
  },
  {
    value: '满足',
    label: '满足',
  },
  {
    value: '壮族',
    label: '壮族',
  },
]
const jobs = [
  {
    value: '施工员',
    label: '施工员',
  },
  {
    value: '会计',
    label: '会计',
  },
  {
    value: '材料员',
    label: '材料员',
  },
  {
    value: '杂工',
    label: '杂工',
  },
  {
    value: '666',
    label: '666',
  },
]
const departments = [
  {
    value: '管理部',
    label: '管理部',
  },
  {
    value: '财务部',
    label: '财务部',
  },
  {
    value: '后勤部',
    label: '后勤部',
  },
  {
    value: '666',
    label: '666',
  },
  {
    value: '777',
    label: '777',
  },
]
const natives = [
  {
    value: '河南省',
    label: '河南省',
  },
  {
    value: '山东省',
    label: '山东省',
  },
  {
    value: '河北省',
    label: '河北省',
  },
  {
    value: '黑龙江省',
    label: '黑龙江省',
  },
  {
    value: '上海',
    label: '上海',
  },
]
const searchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
      if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
        callback(new Error('请填写结束日期'))
      } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
        callback(new Error('请填写开始日期'))
      } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
        callback(new Error('开始日期应当早于结束日期'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
  tel:[

  ]
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}
const openHeaderChange = () => {
  chooseImg.value.open()
}
const chooseImg = ref(null)
const chooseImg2 = ref(null)

const openHeaderChange1 = () => {
  chooseImg2.value.open()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    if (searchInfo.value.accessstatus === ""){
        searchInfo.value.accessstatus=null
    }
    if (searchInfo.value.examstatus === ""){
        searchInfo.value.examstatus=null
    }
    if (searchInfo.value.ishere === ""){
        searchInfo.value.ishere=null
    }
    if (searchInfo.value.outinstatus === ""){
        searchInfo.value.outinstatus=null
    }
    if (searchInfo.value.sex === ""){
        searchInfo.value.sex=null
    }
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  const table = await getStaffList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () =>{
  genderOptions.value = await getDictFunc('gender')
}

// 获取需要的字典 可能为空 按需保留
setOptions()


// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
    ElMessageBox.confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
            deleteStaffFunc(row)
        })
    }


// 批量删除控制标记
const deleteVisible = ref(false)

// 多选删除
const onDelete = async() => {
      const ids = []
      if (multipleSelection.value.length === 0) {
        ElMessage({
          type: 'warning',
          message: '请选择要删除的数据'
        })
        return
      }
      multipleSelection.value &&
        multipleSelection.value.map(item => {
          ids.push(item.ID)
        })
      const res = await deleteStaffByIds({ ids })
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        if (tableData.value.length === ids.length && page.value > 1) {
          page.value--
        }
        deleteVisible.value = false
        getTableData()
      }
    }

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateStaffFunc = async(row) => {
    const res = await findStaff({ ID: row.ID })
    type.value = 'update'
    if (res.code === 0) {
        formData.value = res.data.restaff
        dialogFormVisible.value = true
    }
}

// 删除行
const deleteStaffFunc = async (row) => {
    const res = await deleteStaff({ ID: row.ID })
    if (res.code === 0) {
        ElMessage({
                type: 'success',
                message: '删除成功'
            })
            if (tableData.value.length === 1 && page.value > 1) {
            page.value--
        }
        getTableData()
    }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)


// 查看详情控制标记
const detailShow = ref(false)


// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}


// 打开详情
const getDetails = async (row) => {
  // 打开弹窗
  const res = await findStaff({ ID: row.ID })
  if (res.code === 0) {
    formData.value = res.data.restaff
    openDetailShow()
  }
}


// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  formData.value = {
          accessstatus: false,
          department: '',
          examstatus: false,
          faceimg: '',
          idaddr: '',
          idcard: '',
          idcardimg: '',
          ishere: false,
          job: '',
          nation: '',
          native: '',
          outinstatus: false,
          sex: false,
          tel: '',
          username: '',
          }
}


// 打开弹窗
const openDialog = () => {
    type.value = 'create'
    dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
    dialogFormVisible.value = false
    formData.value = {
        accessstatus: false,
        department: '',
        examstatus: false,
        faceimg: '',
        idaddr: '',
        idcard: '',
        idcardimg: '',
        ishere: false,
        job: '',
        nation: '',
        native: '',
        outinstatus: false,
        sex: false,
        tel: '',
        username: '',
        }
}
// 弹窗确定
const enterDialog = async () => {
     elFormRef.value?.validate( async (valid) => {
             if (!valid) return
              let res
              switch (type.value) {
                case 'create':
                  // console.log(formData.value.tel)
                  //
                  res = await createStaff(formData.value)
                  break
                case 'update':
                  res = await updateStaff(formData.value)
                  break
                default:
                  res = await createStaff(formData.value)
                  break
              }
              if (res.code === 0) {
                ElMessage({
                  type: 'success',
                  message: '创建/更改成功'
                })
                closeDialog()
                getTableData()
              }
      })
}

</script>

<style>

</style>
<style lang="scss">
.header-img-box {
  @apply w-52 h-52 border border-solid border-gray-300 rounded-xl flex justify-center items-center cursor-pointer;
}
</style>